package com.sun.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.bean.Employee;
import com.sun.bean.Msg;
import com.sun.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 处理员工的crud请求
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * 查询员工数据（分页查询）
     *
     * @return
     */
    //@RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
        //引入pagehapper插件
        //传入分页和页码大小
        PageHelper.startPage(pn, 5);
        //starpage 后紧跟的查询就是查询的结果
        List<Employee> employees = employeeService.getAll();
        //使用pageinfo包装查询结果，封装了详细的分页信息，只需将pageinfo交给页面就可
        PageInfo<Employee> page = new PageInfo<>(employees, 5);
        model.addAttribute("pageInfo", page);
        return "list";
    }

    @ResponseBody
    @RequestMapping("/emps")
    public Msg getEmpWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        //引入pagehapper插件
        //传入分页和页码大小
        PageHelper.startPage(pn, 5);
        //starpage 后紧跟的查询就是查询的结果
        List<Employee> employees = employeeService.getAll();
        //使用pageinfo包装查询结果，封装了详细的分页信息，只需将pageinfo交给页面就可
        PageInfo<Employee> page = new PageInfo<>(employees, 5);
        //封装为Msg类
        return Msg.success().add("pageInfo", page);

    }

    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result) {
        if (result.hasErrors()) {
            //校验失败，返回失败信息
            Map<String, Object> map = new HashMap<>(4);
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError filedError : errors) {
                System.out.println("错误字段：" + filedError.getField());
                System.out.println("错误的信息：" + filedError.getDefaultMessage());
                map.put(filedError.getField(), filedError.getDefaultMessage());
            }
            return Msg.fail().add("errorFiled", map);
        }
        int i = employeeService.saveEmp(employee);
        return Msg.success().add("id", i);
    }

    /**
     * 检查用户名是否可用
     *
     * @param empName 用户名
     * @return 校验
     */
    @ResponseBody
    @RequestMapping("/checkUser")
    public Msg checkName(@RequestParam("empName") String empName) {
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";

        if (!empName.matches(regx)) {
            return Msg.fail().add("va_msg", "用户名为2-5位的中文字符或6-16位的英文数字组合");
        }
        boolean b = employeeService.checkUser(empName);
        if (b) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "用户名不可用");
        }
    }
}
